#include <iostream>
using std::cout;
using std::endl;

class Data
{
public:
    Data(int data = 0)
    : _data(data)
    {   cout << "Data(int)" << endl;    }

    ~Data() {cout << "~Data()" << endl; }

    int getData() const {   return _data;   }

private:
    int _data;
};

class MiddleLayer
{
public:
    //假设传递过来的Data*是一个堆空间的对象 
    MiddleLayer(Data * pdata)
    : _pdata(pdata)
    {   cout << "MiddleLayer(Data*)" << endl;    }

    ~MiddleLayer()
    {
        if(_pdata) {
            delete _pdata;
            _pdata = nullptr;
        }
        cout << "~MiddleLayer()" << endl;
    }

    Data * operator->()
    {   return _pdata;  }

    Data & operator*()
    {   return *_pdata; }

private:
    Data * _pdata;
};

class ThirdLayer
{
public:
    //p指针依然是一个堆空间的对象
    ThirdLayer(MiddleLayer * p)
    : _pml(p)
    {   cout << "ThirdLayer()" << endl;}

    //MiddleLayer * operator->()//返回指针不能达到省略箭头的效果
    MiddleLayer & operator->()
    {   return *_pml;   }

    ~ThirdLayer() {
        if(_pml) {
            delete _pml;
            _pml = nullptr;
        }
        cout << "~ThirdLayer()" << endl;
    }

    int getData() const
    {   return 11;}

private:
    MiddleLayer * _pml;
};

void test2()
{
    ThirdLayer * ptl = new ThirdLayer(new MiddleLayer(new Data(1)));
    cout << ptl->getData() << endl;
    cout << (*ptl)->getData() << endl;
}

void test1()
{
    ThirdLayer tl(new MiddleLayer(new Data(100)));
    //tl对象可以一步到位转换成Data*的指针
    cout << tl->getData() << endl;//少写两个箭头

    //cout << ((tl.operator->()).operator->())->getData() << endl;
}

void test0()
{
    //智能指针的雏形: 利用对象的生命周期来管理资源
    MiddleLayer ml(new Data(10));
    cout << ml->getData() << endl;//简写形式
    //完整形式
    //将ml对象直接转换为一个Data*的指针
    cout << (ml.operator->())->getData() << endl;

    cout << (*ml).getData() << endl;
}



int main()
{
    /* test0(); */
    /* test1(); */
    test2();
    return 0;
}

